package proto

import (
//	"github.com/cz-it/gonnectd/src/log"

	"encoding/binary"
	"io"
)

type Head struct {
	Version byte
	Magic   uint16
	Cmd     Uint16
	HeadLen byte
	BodyLen uint16
}

type Body struct {
	Data    []byte
}

type Package struct {
	Head Head
	Body Body
}

func (pkg *Package) ReadHead(r io.Reader) {
	buf := make([]byte, HEADLEN)
	n, err := io.ReadFull(r, buf)
	if n != int(HEADLEN) || err != nil {
		// deal with not enaugh
	}
	pkg.LoadHead(buf)
}

func (pkg *Package) ReadBody(r io.Reader, buffer []byte) {
	len := pkg.Head.BodyLen
	if len == 0 {
		return
	}
	buf := buffer[:len]
	n, err := io.ReadFull(r, buf)
	if n != int(len) || err != nil {
		// deal with not enaugh
	}
	pkg.LoadBody(buf)
}

func (pkg *Package) LoadHead(buf []byte) {
	pkg.Head.Cmd = buf[0]
	pkg.Head.Version = buf[1]
	pkg.Head.Magic = binary.BigEndian.Uint16(buf[2:4])
	pkg.Head.Reserve = buf[4]
	pkg.Head.HeadLen = buf[5]
	pkg.Head.BodyLen = binary.BigEndian.Uint16(buf[6:8])
}

func (pkg *Package) LoadBody(buf []byte) {
	pkg.Body.Data = buf[:]
}
